package com.andy.basics;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.springframework.stereotype.Component;

@Component
public class Validator {

	private javax.validation.Validator validator;

	public Validator() {
		try {
			this.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init() throws Exception {
		ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
		this.validator = validatorFactory.usingContext().getValidator();
	}

	public boolean validate(Object target, MessageHandler messageHandler) {
		Set<ConstraintViolation<Object>> constraintViolations = this.validator.validate(target);
		for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
			String propertyPath = constraintViolation.getPropertyPath().toString();
			String message = constraintViolation.getMessage();
			messageHandler.addMessage(propertyPath, message);
		}
		return constraintViolations.size() <= 0;
	}

}